package com.jkl.webserver.Web.Service;

import com.jkl.webserver.Web.DAO.mapper.AccountMapper;
import com.jkl.webserver.Web.DAO.pojo.Account;
import com.jkl.webserver.Tool.vertifycode.ValidateCode;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Service
public class WebLoginService {
    private final AccountMapper accountMapper;

    public WebLoginService(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    public int WebVerify(HttpServletRequest request, String email, String password){
        Account account=accountMapper.selectPU(email);
        if(account==null){//用户不存在
            return 0;
        }
        else if(!password.equals(account.getPassword())){//密码错误
            return 1;
        }
        else {//密码正确
            HttpSession session= request.getSession();
            session.setAttribute("email", email);
            session.setAttribute("username", account.getUserName());
            return 2;
        }
    }
    public void generateCode(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ValidateCode vc = new ValidateCode(120, 40, 4, 100);
        String code = vc.getCode();
        request.getSession().setAttribute("code", code);
        try (ServletOutputStream os = response.getOutputStream()) {
            vc.write(os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
